package minglue.util

import java.io.BufferedInputStream
import java.io.InputStream
import java.util
import java.util.Properties

import redis.clients.jedis.JedisCluster
import redis.clients.jedis.HostAndPort
object RedisConnector extends Serializable {
  val properties: Properties = new Properties
  val in: InputStream = getClass.getResourceAsStream("/redisCluster.properties")
  properties.load(new BufferedInputStream(in))
  val redisServers = properties.getProperty("redis.servers")
  
  var instances = Map[String, JedisCluster]()

  def nodes2ServerList(nodes: String): util.HashSet[HostAndPort] = {
    val serverList = new util.HashSet[HostAndPort]()
    nodes.split(",").map { x => x.split(":") }.flatMap { ar =>
      {
        if (ar.length == 2) {
          println(ar(0), ar(1))
          Some(ar(0), ar(1))
        } else {
          None
        }
      }
    }.foreach { case (node, port) => serverList.add(new HostAndPort(node, port.toInt)) }
    serverList
  }

  def getConnection(): JedisCluster = {
    val servers = nodes2ServerList(redisServers)
    val client = new JedisCluster(servers)
    client.set("test", "my forst jedis");
    
    instances += redisServers -> client
    client
  }

  def main(args: Array[String]): Unit = {
     val jc = getConnection.get("test");
     println(jc)
  }
}
   